package com.lyw.wechatkf.controller;

import com.lyw.wechatkf.config.properties.BaseWeComProperties;
import com.lyw.wechatkf.entity.MessageResult;
import com.lyw.wechatkf.entity.MessageSend;
import com.lyw.wechatkf.service.MessageService;
import com.lyw.wechatkf.service.UrlTestService;
import com.lyw.wechatkf.vo.KfReceiveMessageVo;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.XMLParse;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
public class UrlTestController {
    private final UrlTestService urlTestService;
    private final MessageService messageService;

    private final BaseWeComProperties baseWeComProperties;

    public UrlTestController(UrlTestService urlTestService, MessageService messageService, BaseWeComProperties baseWeComProperties) {
        this.urlTestService = urlTestService;
        this.messageService = messageService;
        this.baseWeComProperties = baseWeComProperties;
    }

    @RequestMapping("/openReceiveMessage")
    public Object openReceiveMessage(@RequestParam("msg_signature") @Nullable String msg_signature,
                                     @RequestParam("timestamp") @Nullable String timestamp,
                                     @RequestParam("nonce") @Nullable String nonce,
                                     @RequestParam("echostr") @Nullable String echostr,
                                     @RequestBody @Nullable String xml) throws AesException, IOException, SAXException, ParserConfigurationException {
        System.out.println("msg_signature:  "+msg_signature);
        System.out.println("timestamp:  "+timestamp);
        System.out.println("nonce:  "+nonce);
        System.out.println("echostr:  "+echostr);
        System.out.println("xml:  "+xml);
        if (StringUtils.hasText(echostr)){
            String decrypt = urlTestService.decrypt(msg_signature, timestamp, nonce, echostr);
            System.out.println(decrypt);
            return decrypt;
        }else if (StringUtils.hasText(xml)){
            Object[] extract = XMLParse.extract(xml);
            System.out.println("-------");
            String str = (String) extract[1];
            String decrypt = urlTestService.decrypt(msg_signature, timestamp, nonce, str);
            System.out.println("decrypt:  "+decrypt);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(decrypt);
            InputSource is = new InputSource(sr);
            Document document = documentBuilder.parse(is);
            Element root = document.getDocumentElement();
            NodeList toUserNameXml = root.getElementsByTagName("ToUserName");
            String toUserName = toUserNameXml.item(0).getTextContent();
            System.out.println("toUserName:"+toUserName);
            NodeList msgTypeXml = root.getElementsByTagName("MsgType");
            String msgType = msgTypeXml.item(0).getTextContent();
            System.out.println("msgType:"+msgType);

            NodeList eventXml = root.getElementsByTagName("Event");
            String event = eventXml.item(0).getTextContent();
            System.out.println("event:"+event);

            NodeList tokenXml = root.getElementsByTagName("Token");
            String token = tokenXml.item(0).getTextContent();
            System.out.println("token:"+token);
            CompletableFuture.runAsync(()->{
                try {
                    // 获取消息
                    MessageResult messageResult = messageService.getMessage(null, token, null, null, baseWeComProperties.getAccess_token());
                    // 处理消息数据
                    String open_kfid = null;
                    String external_userid = null;
                    List<MessageResult.Msg_list> msg_list = messageResult.getMsg_list();
                    for (MessageResult.Msg_list msgList : msg_list) {
                        MessageResult.Event msgListEvent = msgList.getEvent();
                        if (msgListEvent != null){
                            open_kfid = msgListEvent.getOpen_kfid();
                            external_userid = msgListEvent.getExternal_userid();
                            break;
                        }
                    }
                    System.out.println("open_kfid:"+open_kfid);
                    System.out.println("external_userid:"+external_userid);
                    MessageSend messageSend = new MessageSend();
                    messageSend.setMsgid("asdkhakdhkasd"+System.currentTimeMillis());
                    messageSend.setOpen_kfid(open_kfid);
                    messageSend.setMsgtype("text");
                    messageSend.setTouser(external_userid);
                    MessageSend.Text text = new MessageSend.Text();
                    text.setContent("你好");
                    messageSend.setText(text);
                    messageService.sendMessage(messageSend, baseWeComProperties.getAccess_token());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).exceptionally(throwable -> {
                throwable.printStackTrace();
                return null;
            });

//            String toUserName = (String) extract[0];
//            System.out.println("toUserName:"+toUserName);
        }
        return null;
    }

    @PostMapping ("/useReceiveMessage")
    public void useReceiveMessage(@RequestParam("msg_signature") String msg_signature,
                                  @RequestParam("timestamp") String timestamp,
                                  @RequestParam("nonce") String nonce,
                                  @RequestBody KfReceiveMessageVo kfReceiveMessageVo){

    }

}
